package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.constants.RedisConstant;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {

        // 根据用户查询
        Page<Blog> page =  query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(this::queryBlogByUser);
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if(blog == null){
            return Result.fail("博客不存在");
        }

        // 查询用户
        queryBlogByUser(blog);
//        查询blog是否被当前用户点过赞

        queryBlogLiked(blog);

        return Result.ok(blog);
    }



    @Override
    public Result likeBlog(Long id) {
//        1.获取登录用户
//        2.判断当前用户是否已经点赞
//        3.如果未点赞则点赞
//        4.如果已经点赞，则取消点赞
//        4.1 取消且数据库存储-1
//        4.2 把用户从帖子点赞set集合中删除

        Long userId = UserHolder.getUser().getId();
        String key = RedisConstant.BLOG_LIKED + id;
        Double isMemberScore = stringRedisTemplate.opsForZSet()
                .score(key, userId.toString());

        if(isMemberScore == null){

            boolean isSuccess = update()
                    .setSql("liked = liked + 1")
                    .eq("id", id).update();
            if(isSuccess){
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }

        } else {
            boolean isSuccess = update()
                    .setSql("liked = liked - 1")
                    .eq("id", id).update();
            if(isSuccess){
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }


        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {

        String key = RedisConstant.BLOG_LIKED + id;

//        1.查询出top5点赞用户
        Set<String> likesList = stringRedisTemplate.opsForZSet().range(key, 0 ,4);
//        2.解析出其中的id

        List<Long> ids = null;
        if (likesList == null) {
            return Result.ok(Collections.emptyList());
        }

        ids = likesList.stream().map(Long::valueOf).toList();

        String idStr = StrUtil.join(",", ids);
//        3.根据id返回用户
        List<User> users = userService.query()
                .in("id", ids).last("order by field(id," + idStr + ")").list();


        List<UserDTO> likedUsers = new LinkedList<>();
        users.forEach(user -> {
            UserDTO userDTO = new UserDTO();
            userDTO.setId(user.getId());
            userDTO.setIcon(user.getIcon());
            userDTO.setNickName(user.getNickName());
            likedUsers.add(userDTO);
        });

        return Result.ok(likedUsers);
    }

    @Override
    public Result saveOne(Blog blog) {
                // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess =  save(blog);
        // 返回id

        if(!isSuccess){
            return Result.fail("发布失败");
        }
//        将这个blog发送给所有粉丝的收件箱。

        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();

        follows.forEach(follow -> {
            Long userId = follow.getUserId();
            String key = RedisConstant.FEED_KEY + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        });

        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {

//        先找到当前用户的收件箱
        Long userId = UserHolder.getUser().getId();
//        解析收件箱，获取blogid，获取时间戳
        String key = RedisConstant.FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                            .reverseRangeByScoreWithScores(key, 0, max, offset, 2);

        if(typedTuples == null || typedTuples.isEmpty()){
            log.info("当前收件箱里面没有数据");
            return Result.ok();
        }

        List<Long> ids = new ArrayList<>();
        Long minTime = 0L;
        int os = 1;

        for(ZSetOperations.TypedTuple<String> tuple : typedTuples){
            String idStr = tuple.getValue();
            ids.add(Long.valueOf(idStr));
            Long timeStamp = tuple.getScore().longValue();
            if(timeStamp == minTime){
                os++;
            } else {
                //        找到最小值的重复个数
                minTime = timeStamp;
                os = 1;
            }
        }

//        找到最小时间戳返回前端
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("order by field(id," + idStr + ")").list();
        ScrollResult scrollResult = new ScrollResult();

        //         还要查看blog有没有被点赞
        for(Blog blog : blogs){
            queryBlogLiked(blog);
        }

        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);

        return Result.ok(scrollResult);

    }


    private void queryBlogByUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    private void queryBlogLiked(Blog blog) {
//        判断当前blog的redis set中有没有当前用户
        Long userId = UserHolder.getUser().getId();
        if(userId == null){
            return;
        }

        String key = RedisConstant.BLOG_LIKED + blog.getId();
        Double isMemberScore = stringRedisTemplate.opsForZSet()
                .score(key, userId.toString());

        blog.setIsLike(isMemberScore != null);
    }



}
